﻿using GalaSoft.MvvmLight;
using VolunteerManager.Model;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Windows.Input;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Messaging;
using System.Windows;
using System.Data;
using System;
using Aspose.Cells;
using System.Reflection;

namespace VolunteerManager.ViewModel
{

    public class MainViewModel : ViewModelBase
    {
        private readonly IDataService _dataService;

        private ObservableCollection<Voluteer> _volutterList;

        private ICommand _editCommand;
        private ICommand _delCommand;
        private ICommand _createCommand;
        private ICommand _refurbishCommand;
        private ICommand _searchCommand;
        private ICommand _typeSelectCommand;
        private ICommand _exportCommand;
        private int _total;
        private string _word;


        #region 界面绑定属性
        public int Totla
        {
            get { return _total; }
            set
            {
                _total = value;
                RaisePropertyChanged("Totla");
            }
        }

        public string Word
        {
            get { return _word; }
            set { if (value != _word) { _word = value; RaisePropertyChanged("Word"); } }
        }
        #endregion

        public Voluteer SelectedVolunteer { get; set; }

        #region 命令绑定项目
        public ICommand SearchCommand
        {
            get
            {
                if (null == _searchCommand)
                {
                    _searchCommand = new RelayCommand(() => search());
                }
                return _searchCommand;
            }
        }
        public ICommand SelectedTypeCommand
        {
            get
            {
                if (null == _typeSelectCommand)
                {
                    _typeSelectCommand = new RelayCommand<object>((a) => selectatype(a));
                }
                return _typeSelectCommand;
            }
        }
        public ICommand RefurbishCommand
        {
            get
            {
                if (null == _refurbishCommand)
                {
                    _refurbishCommand = new RelayCommand(() => refurbish());
                }
                return _refurbishCommand;
            }
        }
        public ICommand EditCommand
        {
            get
            {
                if (null == _editCommand)
                {
                    _editCommand = new RelayCommand(() => edit(), () => canEdit());
                }
                return _editCommand;
            }
        }
        public ICommand CreateCommand
        {
            get
            {
                if (null == _createCommand)
                {
                    _createCommand = new RelayCommand(() => create());
                }
                return _createCommand;
            }
        }
        
        public ICommand DeleteCommand
        {
                get
            {
                if (null == _delCommand)
                {
                    _delCommand = new RelayCommand(() => delete(), () => canEdit());
                }
                return _delCommand;
            
            }
        }
        public ICommand ExportCommand
        {
            get
            {
                if (null == _exportCommand)
                {
                    _exportCommand = new RelayCommand(() => export());
                }
                return _exportCommand;
            }
        }
        #endregion

        /// <summary>
        /// 树的条件过渡
        /// </summary>
        /// <param name="a"></param>
        private void selectatype(object a)
        {
            if (a is Group)
            {
                Group b = a as Group;
                int w = b.ID;
                this.VolutterList = new ObservableCollection<Voluteer>(new Voluteer().FindAll2<Voluteer>("GroupID =" + w));
                Word = "";
            }
            else if (a is System.Windows.Controls.TreeViewItem)
            {
                System.Windows.Controls.TreeViewItem b = a as System.Windows.Controls.TreeViewItem;
                if (b.Tag != null)
                {
                    if (b.Tag.ToString() == "-1")
                    {
                        refurbish();
                    }
                }
                else
                {
                    string w = b.Header.ToString();

                    this.VolutterList = new ObservableCollection<Voluteer>(new Voluteer().FindAll2<Voluteer>("Models LIKE '%" + w + "%'"));
                    Word = "";
                }
            }
            else if (a is Model.Point)
            {

            }
            
        }

        private void search()
        {
            this.VolutterList = new ObservableCollection<Voluteer>(new Voluteer().FindAll2<Voluteer>("SearchWord LIKE '%" + Word + "%'"));
        }

        /// <summary>
        /// 刷新界面内容
        /// </summary>
        private void refurbish()
        {
            Voluteer v = new Voluteer();
            this.VolutterList = new ObservableCollection<Voluteer>(_dataService.VolutterList);
            Totla = v.Count("1=1");
        }

        private void create()
        {
            WinCreateVolunteer win = new WinCreateVolunteer();
            Messenger.Default.Send<object>(new Voluteer(), "LoadInfo");
            win.ShowDialog();
            this.refurbish();
        }
        
        private void edit()
        {
            WinCreateVolunteer win = new WinCreateVolunteer();
            Messenger.Default.Send<object>(this.SelectedVolunteer, "LoadInfo");
            win.ShowDialog();
        }

        private void delete()
        {
            if (System.Windows.MessageBox.Show("删除 " + SelectedVolunteer.Name + " 的信息吗?", "系统提示", System.Windows.MessageBoxButton.OKCancel, System.Windows.MessageBoxImage.Warning)
                == System.Windows.MessageBoxResult.OK)
            {
                if (SelectedVolunteer.Delete("ID", SelectedVolunteer.ID))
                {
                    System.Windows.MessageBox.Show("已删除", "系统提示", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Information);
                    this.VolutterList.Remove(SelectedVolunteer);
                    Totla = _total - 1;
                }
            }
        }
 

        private bool canEdit()
        {
            return this.SelectedVolunteer != null;
        }

        public ObservableCollection<Voluteer> VolutterList
        {
            get
            {
                return _volutterList;
            }
            set
            {
                _volutterList = value;
                RaisePropertyChanged("VolutterList");
            }
        }

        public MainViewModel(IDataService dataService)
        {
            _dataService = dataService;
            refurbish();

        }

        ////public override void Cleanup()
        ////{
        ////    // Clean up if needed

        ////    base.Cleanup();
        ////}


        /// <summary>
        /// 导出  区分导出所有 和导出 部分？
        /// </summary>
        private void export()
        {
            Microsoft.Win32.SaveFileDialog dialg = new Microsoft.Win32.SaveFileDialog();
            dialg.ValidateNames = true;
            dialg.Filter = "xls文件|*.xls";
            bool? res = dialg.ShowDialog();

            if (res.Value)
            {

                string filepath = dialg.FileName;
                

                Workbook book = new Workbook();
                Worksheet sheet = book.Worksheets[0];

                string[] titles = new string[] { "姓名", "微信名", "性别", "名族", "籍贯", "出生年月", "QQ号码", "加入时间", "行业", "职业", "邮箱", "擅长" };
                int row = 0;
                for (int i = 0; i < titles.Length; i++)
                {
                    Cell cell = sheet.Cells[row, i];
                    cell.PutValue(titles[i]);
                }

                foreach (var vol in this.VolutterList)
                {
                    row++;
                    Voluteer v = vol as Voluteer;
                    string[] values = new string[] { 
                    v.Name, v.Wechat, v.Sex.ToString(), v.Peoples.ToString(), v.Regions, v.Birth.ToLongDateString(), v.QQ, v.JoinDate.ToShortDateString(), v.Professional, v.Vocation, v.Email, v.Models
                };
                    for (int i = 0; i < values.Length; i++)
                    {

                        Cell cell = sheet.Cells[row, i];
                        cell.PutValue(values[i]);
                    }

                }

                ////dt.Rows.Add(new Data { ItemArray =  new object[]{ "123", "4456", "689"} });

                //Cell cell1 = sheet.Cells[0, 0];

                ////cell1.PutValue(title);
                //cell1.GetStyle().HorizontalAlignment = TextAlignmentType.Center;
                //cell1.GetStyle().Font.Name = "黑体";
                //cell1.GetStyle().Font.Size = 14;
                //cell1.GetStyle().Font.IsBold = true;

                //Cell cell2 = sheet.Cells[1, 0];
                //cell1.PutValue("查询时间：" + DateTime.Now.ToLocalTime());
                //cell2.SetStyle(cell1.GetStyle());
                try
                {
                    book.Save(filepath);
                    MessageBox.Show("已导出", "系统提示");
                }
                catch (Exception ex)
                {

                    MessageBox.Show("系统提示", "操作失败\r\n" + ex.Message);
                }
            }
        }
    }
}